package com.quaidi.smartlocker.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.quaidi.smartlocker.annotation.RequireRole;
import com.quaidi.smartlocker.common.Result;
import com.quaidi.smartlocker.enums.UserRole;
import com.quaidi.smartlocker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 权限验证拦截器
 * 
 * @author QuaiDi
 * @since 2025-08-26
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequireRole requireRole = handlerMethod.getMethodAnnotation(RequireRole.class);
        
        if (requireRole == null) {
            // 没有权限注解，允许访问
            return true;
        }

        HttpSession session = request.getSession();
        UserRole[] requiredRoles = requireRole.value();
        
        // 检查用户是否有任一所需角色
        for (UserRole role : requiredRoles) {
            if (userService.hasRole(session, role)) {
                return true;
            }
        }

        // 权限不足，返回错误
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        
        Result<String> result = Result.error(403, "权限不足，请联系管理员");
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(result));
        
        return false;
    }
}